package com.wzq.animal.back.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.animal.back.pojo.Files;
import com.wzq.animal.back.service.FilesService;
import com.wzq.animal.common.Result;
import com.wzq.animal.common.exception.GlobalException;
import com.wzq.animal.common.exception.StatusCode;
import com.wzq.animal.utils.MyOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FilesService filesService;

    //@Value("${files.upload.path}")
    //private String fileUploadPath;

    private String excel = "https://sxanimals.oss-cn-hangzhou.aliyuncs.com/fileIcon/excel.png";
    private String word = "https://sxanimals.oss-cn-hangzhou.aliyuncs.com/fileIcon/word.png";
    private String pdf = "https://sxanimals.oss-cn-hangzhou.aliyuncs.com/fileIcon/pdf.png";
    private String txt = "https://sxanimals.oss-cn-hangzhou.aliyuncs.com/fileIcon/txt.png";
    private String other = "https://sxanimals.oss-cn-hangzhou.aliyuncs.com/fileIcon/other.png";

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        //String originalFilename = file.getOriginalFilename();//获取文件原始名称
        //String mainName = FileUtil.mainName(originalFilename);//不带后缀的文件名
        //String type = FileUtil.extName(originalFilename);//获取文件类型
        //long size = file.getSize();//获取文件大小
        ////存储到磁盘
        //File uploadParentFile = new File(fileUploadPath);
        ////判断文件目录是否存在，若不存在则创建一个新的文件目录
        //if (!uploadParentFile.exists()) {
        //    uploadParentFile.mkdirs();
        //}
        //// 定义一个文件唯一的标识码
        //String uuid = IdUtil.fastSimpleUUID();
        //File uploadFile = new File(uploadParentFile + File.separator + uuid + StrUtil.DOT + type);
        //String fileUrl = "http://localhost:9191/files/" + uuid + StrUtil.DOT + type;
        //Files files = new Files();
        //file.transferTo(uploadFile);
        ////获取文件的 md5
        //String fileMd5 = SecureUtil.md5(uploadFile);
        ////根据 md5 查询数据库中是否有相同文件
        //if (getFilesByMd5(fileMd5).size() > 0) {
        //    uploadFile.delete();
        //    throw new GlobalException(StatusCode.FILE_EXISTS,getFilesByMd5(fileMd5).get(0).getUrl());
        //} else {
        //    files.setOriginalName(mainName);
        //    files.setUuidName(uuid);
        //    files.setSize(size / 1024);
        //    files.setType(type);
        //    files.setUrl(fileUrl);
        //    files.setMd5(fileMd5);
        //    filesService.save(files);
        //    return Result.success(fileUrl);
        //}

        String fileUrl = MyOSSUtils.uploadFile(file, "other");
        String originalFilename = file.getOriginalFilename();//获取文件原始名称
        String mainName = FileUtil.mainName(originalFilename);//不带后缀的文件名
        String type = FileUtil.extName(originalFilename);//获取文件类型
        long size = file.getSize();//获取文件大小
        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        //获取文件的 md5
        String fileMd5 = SecureUtil.md5(fileUrl);
        Files files = new Files();
        files.setOriginalName(mainName);
        files.setUuidName(uuid);
        files.setSize(size / 1024);
        files.setType(type);
        files.setUrl(fileUrl);
        files.setMd5(fileMd5);
        if(type.equals("jpg") || type.equals("jpeg") || type.equals("png") || type.equals("gif")){
            files.setShowImg(fileUrl);
        }else if(type.equals("doc") || type.equals("docx")){
            files.setShowImg(word);
        }else if(type.equals("xlsx")){
            files.setShowImg(excel);
        }else if(type.equals("pdf")){
            files.setShowImg(pdf);
        }else if(type.equals("txt")){
            files.setShowImg(txt);
        }else{
            files.setShowImg(other);
        }
        filesService.save(files);
        return Result.success(fileUrl);
    }

    /**
     * 文件下载接口 http://localhost:9191/files/{fileUUID}
     *
     * @param fileUUID
     * @param response
     * @return
     * @throws IOException
     */
    //@GetMapping("/{fileUUID}")
    //public Result download(@PathVariable("fileUUID") String fileUUID, HttpServletResponse response) throws IOException {
    //    //根据文件唯一标识码获取文件
    //    File uploadFile = new File(fileUploadPath + fileUUID);
    //    //设置输出流的格式
    //    ServletOutputStream os = response.getOutputStream();
    //    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
    //    response.setContentType("application/octet-stream");
    //
    //    //读取文件的字节流
    //    os.write(FileUtil.readBytes(uploadFile));
    //    os.flush();
    //    os.close();
    //    return Result.success();
    //}

    /**
     * 根据 md5 从数据库查询文件
     *
     * @param md5
     * @return
     */
    public List<Files> getFilesByMd5(String md5) {
        //根据文件的 md5 从数据库查询是否有相同文件
        LambdaQueryWrapper<Files> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Files::getMd5, md5);
        List<Files> list = filesService.list(queryWrapper);
        return list;
    }

    /**
     * 获取文件分页数据
     *
     * @param currentPage
     * @param pageSize
     * @param fileName
     * @param fileType
     * @return
     */
    @GetMapping("/getPages/{currentPage}/{pageSize}")
    public Result getPages(@PathVariable("currentPage") int currentPage,
                           @PathVariable("pageSize") int pageSize,
                           @RequestParam("fileName") String fileName,
                           @RequestParam("fileType") String fileType) {
        Page<Files> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("original_name", fileName)
                .like("type", fileType);
        filesService.page(page, queryWrapper);
        return Result.success(page);
    }

    /**
     * 删除文件
     *
     * @param id 文件 id
     * @return
     */
    @DeleteMapping("/delFile/{id}")
    public Result delFile(@PathVariable("id") int id) {
        filesService.removeById(id);
        return Result.success();
    }

    /**
     * 根据 id 修改原始文件名
     *
     * @param id
     * @param originalName
     * @return
     */
    @PostMapping("/updateOriginalName/{id}/{originalName}")
    public Result updateOriginalName(@PathVariable("id") int id, @PathVariable("originalName") String originalName) {
        boolean res = filesService.updateOriginalMainName(id, originalName);
        return res == true ? Result.success() : Result.error(StatusCode.FILE_UPDATE.getCode(), StatusCode.FILE_UPDATE.getMsg());
    }
}
